package com.funeral.diyaccount.url.dao;

import com.funeral.diyaccount.base.dao.BaseDao;
import com.funeral.diyaccount.base.exception.DaoException;
import com.funeral.diyaccount.common.page.pojo.PageObject;
import com.funeral.diyaccount.url.entity.TDAUrl;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by peizangpin on 2017/5/4.
 */
@Repository
public class UrlDao extends BaseDao<TDAUrl,Long> {
    @Resource
    private UrlDaoInfo urlDaoInfo;

    @PostConstruct
    public void init(){
        this.setIdName(urlDaoInfo.getIdName());
        this.setTableName(urlDaoInfo.getTableName());
        this.setSequenceName(urlDaoInfo.getSequenceName());
        this.setRowMapper(urlDaoInfo.getRowMapper());
    }

    public PageObject<TDAUrl> queryUrlListByPage(PageObject<TDAUrl> pageObject, JSONObject jsonFilter)throws DaoException {
        if(pageObject == null ){throw new DaoException("Invalid pageObject!");}
        if(jsonFilter == null){throw new DaoException("Invalid jsonFilter");}
        Object urlidObj = jsonFilter.get("urlid");
        Long urlid =  (urlidObj == null || StringUtils.isBlank(String.valueOf(urlidObj)) == true ) ? null : Long.valueOf(String.valueOf(urlidObj));

        List<Object> params = new ArrayList<Object>();
        StringBuffer sql = new StringBuffer("select * from :tableName ");
        sql.replace(sql.indexOf(":tableName"),sql.indexOf(":tableName")+":tableNmae".length(),this.getTableName());

        StringBuffer and = new StringBuffer();
        if(urlid != null){
            and.append(" and urlid = ? ");
            params.add(urlid);
        }

        if(StringUtils.isNotBlank(and.toString())){
            sql.append(" where 1 = 1 ");
            sql.append(and);
        }
        pageObject = super.queryListSqlWithPage(sql.toString(), pageObject, params.toArray());

        return pageObject;
    }

    @Transactional
    public Long saveUrl(TDAUrl url)throws DaoException{
        Long urlid = null;
        List<TDAUrl> urls = new ArrayList<TDAUrl>();
        urls.add(url);
        urls.add(url);
        urls.add(url);
        super.saveEntitys(urls);

        return urlid;
    }

    public void delUrl(Long id)throws DaoException{
        super.delEntity(id);
    }

}
